package com.lwj.mallchat.common.user.service.impl;

import com.lwj.mallchat.common.user.dao.UserDao;
import com.lwj.mallchat.common.user.domain.entity.User;
import com.lwj.mallchat.common.user.service.UserService;
import com.lwj.mallchat.common.user.service.WxMsgService;
import com.lwj.mallchat.common.user.service.adapter.TextBuilder;
import com.lwj.mallchat.common.user.service.adapter.UserAdapter;
import com.lwj.mallchat.common.websocket.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lwj
 * @ClassName WxMsgServiceImpl
 * @date 2024/10/17 15:57
 */

@Service
@Slf4j
public class WxMsgServiceImpl implements WxMsgService {

    /**
     * openid跟登录code的关系map
     */
    private static final ConcurrentHashMap<String, Integer> WAIT_AUTHORIZE_MAP = new ConcurrentHashMap<>();

    private static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    @Value("${wx.mp.callback}")
    private String callback;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private WebSocketService webSocketService;

    @Override
    public WxMpXmlOutMessage scan(WxMpService wxMpService, WxMpXmlMessage wxMpXmlMessage) {
//        String code = wxMpXmlMessage.getEventKey();
        String open_id = wxMpXmlMessage.getFromUser();
        Integer eventKey = getEventCode(wxMpXmlMessage);
        if (Objects.isNull(eventKey)) {
            return null;
        }
        User user = userDao.getByOpenId(open_id);

        boolean isReg = Objects.nonNull(user);
        //用户已注册且授权
        if (isReg) {
            boolean isAuth = (Objects.nonNull(user.getAvatar()));
            if (isAuth) {
                //走登陆成功逻辑 todo
                webSocketService.scanLogSuccess(eventKey, user.getId());
                return null;
            } else {
                //走授权逻辑 todo

            }
        }
        //用户未注册先注册
        else {
            User save = UserAdapter.buildUserSave(open_id);
            userService.register(save);
        }
        //推送链接让用户授权
        WAIT_AUTHORIZE_MAP.put(open_id, eventKey);
        webSocketService.waitAuthorize(eventKey);
        String authUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback + "/wx/portal/public/callBack"));
        String content = "请点击登录: <a href=\"" + authUrl + "\">登录</a>";
        return TextBuilder.build(content, wxMpXmlMessage);

    }

    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.getByOpenId(openid);
        fillUserInfo(user, userInfo);
        //通过code找到channel，进行登录
        Integer code = WAIT_AUTHORIZE_MAP.remove(openid);
        webSocketService.scanLogSuccess(code,user.getId());
    }

    public void fillUserInfo(User user, WxOAuth2UserInfo userInfo) {
        if (Objects.isNull(user.getAvatar()) || Objects.isNull(user.getName())) {
            user.setName(userInfo.getNickname());
            user.setAvatar(userInfo.getHeadImgUrl());
            userDao.updateById(user);
        }
    }


    private Integer getEventCode(WxMpXmlMessage wxMpXmlMessage) {
        try {
            return Integer.valueOf(wxMpXmlMessage.getEventKey().replace("qrscene_", ""));
        } catch (Exception e) {
            log.error("getEventKey error eventKey:{} ", wxMpXmlMessage.getEventKey(), e);
        }
        return null;
    }
}
